#!/usr/bin/env python

import config
import datastore
import json

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class QuerySpotsListPage(webapp.RequestHandler):
    def _error(self, msg):
        self.response.out.write(json.dumps({'msg': msg}))

    def get(self):
        query = datastore.HotSpotCategory.all()
        categories = query.fetch(config.MAX_SPOT_CATEGORY_NUM)

        categories_listing = []
        for category in categories:
            spots = category.spot_set.fetch(config.MAX_SPOT_LIST_NUM)
            spots_count = category.spot_set.count()

            categories_listing.append({
                'key': str(category.key()),
                'name': category.name,
                'top_spots': map(lambda x: { 'key': str(x.key()),
                                             'name': x.name,
                                             'lat': x.location.lat,
                                             'lon': x.location.lon }, spots),
                'spots_count': spots_count
            });

        self.response.out.write(json.dumps(categories_listing))
